﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using GalaSoft.MvvmLight;
using iTextSharp.text;
using iTextSharp.text.pdf;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Microsoft.Win32;

namespace LiveChartsDemo.ViewModels
{
    class ChartsViewModel:ViewModelBase
    {
        public ChartsViewModel()
        {
            //ChartGroup.Add("条形图");
            //ChartGroup.Add("折线图");
            //ChartGroup.Add("饼图");
            //ChartGroup.Add("散点图");
            //TestList.Add("1");
            //TestList.Add("2");

            //A.B = new List<tB>();
            //A.B.Add(new tB() { value1 = 1 });
        }

        #region 数据绑定
        /// <summary>
        /// 图表类型列表
        /// </summary>
        public List<string> ChartGroup { get { return _ChartGroup; } set { _ChartGroup = value; RaisePropertyChanged("ChartGroup"); } }
        private List<string> _ChartGroup = new List<string>();

        /// <summary>
        /// 条形图图表信息
        /// </summary>
        public ChartInfo BarChartInfo { get { return _BarChartInfo; } set { _BarChartInfo = value; RaisePropertyChanged("BarChartInfo"); } }
        private ChartInfo _BarChartInfo = new ChartInfo();

        /// <summary>
        /// 折线图图表信息
        /// </summary>
        public ChartInfo LineChartInfo { get { return _LineChartInfo; } set { _LineChartInfo = value; RaisePropertyChanged("LineChartInfo"); } }
        private ChartInfo _LineChartInfo = new ChartInfo();

        /// <summary>
        /// 饼图图表信息
        /// </summary>
        public ChartInfo PieChartInfo { get { return _PieChartInfo; } set { _PieChartInfo = value; RaisePropertyChanged("PieChartInfo"); } }
        private ChartInfo _PieChartInfo = new ChartInfo();

        /// <summary>
        /// 散点图的点的集合
        /// </summary>
        public ChartValues<ObservablePoint> ValuesA { get { return _ValuesA; } set { _ValuesA = value; RaisePropertyChanged("ValuesA"); } }
        private ChartValues<ObservablePoint> _ValuesA = new ChartValues<ObservablePoint>();

        /// <summary>
        /// 散点图的点的集合
        /// </summary>
        public ChartValues<ObservablePoint> ValuesB { get { return _ValuesB; } set { _ValuesB = value; RaisePropertyChanged("ValuesB"); } }
        private ChartValues<ObservablePoint> _ValuesB = new ChartValues<ObservablePoint>();

        /// <summary>
        /// 散点图的点的集合
        /// </summary>
        public ChartValues<ObservablePoint> ValuesC { get { return _ValuesC; } set { _ValuesC = value; RaisePropertyChanged("ValuesC"); } }
        private ChartValues<ObservablePoint> _ValuesC = new ChartValues<ObservablePoint>();

        /// <summary>
        /// 测试
        /// </summary>
        public string TestValue { get { return _TestValue; } set { _TestValue = value; RaisePropertyChanged("TestValue"); } }
        private string _TestValue = "";

        /// <summary>
        /// 测试集合
        /// </summary>
        public ChartValues<string> TestList { get { return _TestList; } set { _TestList = value; RaisePropertyChanged("TestList"); } }
        private ChartValues<string> _TestList = new ChartValues<string>();

        public tA A { get { return _A; } set { _A = value; RaisePropertyChanged("A"); } }
        private tA _A = new tA();
        #endregion

        #region 逻辑主体
        /// <summary>
        /// 导入acv
        /// </summary>
        public void InputAcv()
        {
            // 选择ACV
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "ACV|*.acv;";
            dialog.ShowDialog();
            if (dialog.FileName.Length <= 7)
                return;
            string acvPath = dialog.FileName;
            // 读取acv
            if (!File.Exists(acvPath))
                return;
            string[] content = null;
            byte[] binResult = File2Bytes(acvPath);
            string newFilePath = @"C:\Users\Administrator\Desktop\" + Guid.NewGuid().ToString() + ".txt";
            Trace.WriteLine(newFilePath);
            Bytes2File(binResult, newFilePath);
        }

        /// 
        /// 文件转为 二进制
        /// 
        /// 文件路径
        /// 
        public static byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }
            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];
            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return buff;
        }
        /// 
        /// 将byte数组转换为文件并保存到指定地址
        /// 
        /// byte数组
        /// 保存地址
        public static void Bytes2File(byte[] buff, string savepath)
        {
            //if (System.IO.File.Exists(savepath))
            //{
            //    System.IO.File.Delete(savepath);
            //}
            //FileStream fs = new FileStream(savepath, FileMode.CreateNew);
            //BinaryWriter bw = new BinaryWriter(fs, Encoding.);
            //bw.Write(buff, 0, buff.Length);
            //bw.Close();
            //fs.Close();
        }

        public void ChangeIndex()
        {
            Trace.WriteLine("选项改变");
        }

        public void BBaaa()
        {
            // 注册（中文显示用）                 
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //指定字体库，并创建字体(中文显示用)                 
            //BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);                 
            //iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 18);
            BaseFont baseFont = BaseFont.CreateFont(@"E:\CODE\DONET\MySelf\study-demo\LiveChartsDemo\Resources\font\AlibabaSans.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 18);

            // 新建一个A4大小的PDF页面
            Document document = new Document(PageSize.A4);
            try
            {
                // 获取一个PDF页面，输出流
                PdfWriter.GetInstance(document, new FileStream(@"d:\TableWidthAlignment.pdf", FileMode.Create));
                // 打开PDF文档
                document.Open();
                // 新建一个3列的表格
                PdfPTable table = new PdfPTable(3);
                // 插入一行文本，横跨3列
                PdfPCell cell = new PdfPCell(new Paragraph("header with colspan3"));
                cell.Colspan = 3;
                // 将单元格添加到表格
                table.AddCell(cell);
                table.AddCell(new PdfPCell(new Paragraph("姓名1", titleFont)));
                table.AddCell("2.1");
                table.AddCell("3.1");
                table.AddCell("1.2");
                table.AddCell("2.2");
                table.AddCell("3.2");
                // 将表格添加到PDF文档
                document.Add(table);
            }
            catch (Exception de)
            {
                Console.WriteLine(de.Message);
            }
            // 关闭输出流
            document.Close();
        }
        /// <summary>
        /// 生成当前选择的图表类型
        /// </summary>
        /// <param name="chartsKind">选择的图表类型的索引</param>
        public void ChoiceCharts(int chartsIndex)
        {
            TestValue = "2";
            switch (chartsIndex)
            {
                case (int)EnumChartsKind.BarChart:
                    CreateBarChart();
                    break;
                case (int)EnumChartsKind.LineChart:
                    CreateLineChart();
                    break;
                case (int)EnumChartsKind.PieChart:
                    CreatePieChart();
                    break;
                case (int)EnumChartsKind.PointChart:
                    CreatePointChart();
                    break;
                default:break;
            }
        }

        /// <summary>
        /// 生成条形图
        /// </summary>
        private void CreateBarChart()
        {
            SeriesCollection SeriesCollection = new SeriesCollection
            {
                new ColumnSeries
                {
                    Title = "深圳",
                    Values = new ChartValues<double> { 10, 50, 39, 50 }
                },
                new ColumnSeries
            {
                Title = "广州",
                Values = new ChartValues<double> { 11, 56, 42 }
            }
            };

            string[] Labels = new[] { "2011", "2012", "2013", "2014", "2015" };
            BarChartInfo.Series = SeriesCollection;
            BarChartInfo.XLables = Labels;
            BarChartInfo = BarChartInfo;
        }

        /// <summary>
        /// 生成折线图
        /// </summary>
        private void CreateLineChart()
        {
            SeriesCollection series = new SeriesCollection
            {
                new LineSeries
                {
                    Title = "深圳",
                    Values = new ChartValues<double> { 4, 6, 5, 2 ,7 }
                },
                new LineSeries
                {
                    Title = "广州",
                    Values = new ChartValues<double> { 6, 7, 3, 4 ,6 }
                }
            };

            //x轴
            string[] Labels = new[] { "2011", "2012", "2013", "2014", "2015" };
            LineChartInfo.Series = series;
            LineChartInfo.XLables = Labels;
            LineChartInfo = LineChartInfo;
        }

        /// <summary>
        /// 生成饼图
        /// </summary>
        private void CreatePieChart()
        {
            SeriesCollection SeriesCollection = new SeriesCollection();

            SeriesCollection.Add(new PieSeries()
            {
                Title = "高一(1)班",
                Values = new ChartValues<int>() { 30 },
                DataLabels = true,
                LabelPoint = new Func<ChartPoint, string>((chartPoint) =>
                {
                    return string.Format("{0}{1} ({2:P})", chartPoint.SeriesView.Title, chartPoint.Y, chartPoint.Participation);
                })
            });
            SeriesCollection.Add(new PieSeries()
            {
                Title = "高一(2)班",
                Values = new ChartValues<int>() { 50 },
                DataLabels = true,
                LabelPoint = new Func<ChartPoint, string>((chartPoint) =>
                {
                    return string.Format("{0}{1} ({2:P})", chartPoint.SeriesView.Title, chartPoint.Y, chartPoint.Participation);
                })
            });
            SeriesCollection.Add(new PieSeries()
            {
                Title = "高一(3)班",
                Values = new ChartValues<int>() { 20 },
                DataLabels = true,
                LabelPoint = new Func<ChartPoint, string>((chartPoint) =>
                {
                    return string.Format("{0}{1} ({2:P})", chartPoint.SeriesView.Title, chartPoint.Y, chartPoint.Participation);
                })
            });

            PieChartInfo.Series = SeriesCollection;
            PieChartInfo = PieChartInfo;
        }

        /// <summary>
        /// 生成散点图
        /// </summary>
        private void CreatePointChart()
        {
            var r = new Random();
            ValuesA = new ChartValues<ObservablePoint>();
            ValuesB = new ChartValues<ObservablePoint>();
            ValuesC = new ChartValues<ObservablePoint>();

            for (var i = 0; i < 20; i++)
            {
                ValuesA.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
                ValuesB.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
                ValuesC.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
            }
        }
        #endregion
    }


    /// <summary>
    /// 图表信息
    /// </summary>
    public class ChartInfo
    {
        /// <summary>
        /// 图表主体
        /// </summary>
        public SeriesCollection Series { get; set; }
        /// <summary>
        /// X坐标轴标签列表
        /// </summary>
        public string[] XLables { get; set; }
        /// <summary>
        /// X轴步长
        /// </summary>
        public int XStep { get; set; }
        /// <summary>
        /// X轴图表标签格式
        /// </summary>
        public Func<double, string> LabelFormatter { get; set; }
        /// <summary>
        /// Y坐标轴标签列表
        /// </summary>
        public string[] YLables { get; set; }      
        /// <summary>
        /// Y轴步长
        /// </summary>
        public int YStep { get; set; }
        /// <summary>
        /// Y轴图表标签格式
        /// </summary>
        public Func<double, string> YLabelFormatter { get; set; }
    }


    /// <summary>
    /// 图表类型
    /// </summary>
    enum EnumChartsKind
    {
        /// <summary>
        /// 条形图
        /// </summary>
        BarChart,
        /// <summary>
        /// 折线图
        /// </summary>
        LineChart,
        /// <summary>
        /// 饼图
        /// </summary>
        PieChart,
        /// <summary>
        /// 散点图
        /// </summary>
        PointChart,
    }

    public class tA
    {
        public List<tB> B { get; set; }
    }

    public class tB
    {
        public double value1 { get; set; }
    }
}
